package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.pojo.dto.ColumnSetListDTO;
import com.xbongbong.paas.pojo.vo.ColumnSetListVO;
import com.xbongbong.paas.service.UserConfigExplainService;
import com.xbongbong.paas.service.UserConfigService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.SmartReplenishmentEnum;
import com.xbongbong.saas.enums.business.WaitInstockEnum;
import com.xbongbong.saas.enums.business.WaitOutstockEnum;
import com.xbongbong.saas.enums.business.WaitPurchaseContractEnum;
import com.xbongbong.saas.enums.business.WaitPurchaseProductEnum;
import com.xbongbong.sys.enums.UserConfigEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2022/02/14 15:38
 */
@Service("userConfigExplainService")
public class UserConfigExplainServiceImpl implements UserConfigExplainService {

    private static final Logger LOG = LoggerFactory.getLogger(UserConfigExplainServiceImpl.class);

    @Resource
    private UserConfigService userConfigService;

    @Override
    public void setFixedAndInvisible(ColumnSetListDTO columnSetListDTO, List<FieldAttrEntity> headList) throws XbbException {
        try {
            if (Objects.equals(columnSetListDTO.getSubBusinessType(), XbbRefTypeEnum.WARNING_SEARCH.getCode()) || Objects.equals(columnSetListDTO.getSubBusinessType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())) {
                // 个人配置接口，预警查询，保质期查询用的都是库存查询的
                columnSetListDTO.setSubBusinessType(XbbRefTypeEnum.STOCK_SEARCH.getCode());
            }
            ColumnSetListVO columnSetListVO = userConfigService.columnSetList(columnSetListDTO);
            Map<String, Object> userConfigMap = columnSetListVO.getUserConfigMap();
            if (userConfigMap != null) {
                //用户配置 隐藏列
                JSONArray invisibleField = JSONArray.parseArray(JSON.toJSONString(userConfigMap.getOrDefault(UserConfigEnum.COLUMN_INVISIBLE_FIELD.getAlias(), new JSONArray())));
                //用户配置 冻结列
                Integer fixNum = (Integer) userConfigMap.getOrDefault(UserConfigEnum.COLUMN_FIXED_FIELD.getAlias(), 0);
                List<FieldAttrEntity> visibleFieldAttrEntity = new ArrayList<>();
                headList.forEach(item-> {
                    //设置隐藏列
                    if (invisibleField.contains(item.getAttr())) {
                        item.setVisible(0);
                    } else {
                        visibleFieldAttrEntity.add(item);
                    }
                });
                if (fixNum >= visibleFieldAttrEntity.size()) {
                    fixNum = visibleFieldAttrEntity.size();
                }
                List<FieldAttrEntity> fixedFieldAttrEntity = visibleFieldAttrEntity.subList(0, fixNum);
                headList.forEach(item -> {
                    if (fixedFieldAttrEntity.contains(item)) {
                        item.setFixed(true);
                    }
                });
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("列表冻结发生异常：", e);
        }
    }


    @Override
    public void explainFieldSort(ColumnSetListDTO columnSetListDTO, List<FieldAttrEntity> headList) throws XbbException{
        if (Objects.equals(columnSetListDTO.getSubBusinessType(), XbbRefTypeEnum.WARNING_SEARCH.getCode())) {
            // 个人配置接口，预警查询，保质期查询用的都是库存查询的
            columnSetListDTO.setSubBusinessType(XbbRefTypeEnum.STOCK_SEARCH.getCode());
        }
        ColumnSetListVO columnSetListVO = userConfigService.columnSetList(columnSetListDTO);
        Map<String, Object> userConfigMap = columnSetListVO.getUserConfigMap();
        JSONArray fieldSort = (JSONArray) userConfigMap.getOrDefault(UserConfigEnum.COLUMN_SORT_FIELD.getAlias(), new JSONArray());
        if ((Objects.isNull(fieldSort) || fieldSort.isEmpty())
                && Objects.equals(columnSetListDTO.getSubBusinessType(),XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getCode())){
            for (FieldAttrEntity fieldAttrEntity : headList){
                Integer sort = WaitInstockEnum.getSortByWaitInstockSort(fieldAttrEntity.getAttr());
                fieldAttrEntity.setSort(sort);
            }
            headList.sort(Comparator.comparingInt(FieldAttrEntity::getSort));
        }
        if ((Objects.isNull(fieldSort) || fieldSort.isEmpty())
                && Objects.equals(columnSetListDTO.getSubBusinessType(),XbbRefTypeEnum.WAIT_OUTSTOCK.getCode()) && Objects.equals(columnSetListDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())){
            for (FieldAttrEntity fieldAttrEntity : headList){
                Integer sort = WaitOutstockEnum.getSortByWaitInstockSort(fieldAttrEntity.getAttr());
                fieldAttrEntity.setSort(sort);
            }
            headList.sort(Comparator.comparingInt(FieldAttrEntity::getSort));
        }
        // 以销定购合同视图排序
        if ((Objects.isNull(fieldSort) || fieldSort.isEmpty())
                && Objects.equals(columnSetListDTO.getSubBusinessType(),XbbRefTypeEnum.WAIT_PURCHASE.getCode()) && Objects.equals(columnSetListDTO.getBusinessType(),XbbRefTypeEnum.CONTRACT.getCode())){
            for (FieldAttrEntity fieldAttrEntity : headList){
                Integer sort = WaitPurchaseContractEnum.getSortByWaitPurchaseContractSort(fieldAttrEntity.getAttr());
                fieldAttrEntity.setSort(sort);
            }
            headList.sort(Comparator.comparingInt(FieldAttrEntity::getSort));
        }
        // 以销定购合同+产品视图排序
        if ((Objects.isNull(fieldSort) || fieldSort.isEmpty())
                && Objects.equals(columnSetListDTO.getSubBusinessType(),XbbRefTypeEnum.WAIT_PURCHASE.getCode()) && Objects.equals(columnSetListDTO.getBusinessType(),XbbRefTypeEnum.CONTACT.getCode())){
            for (FieldAttrEntity fieldAttrEntity : headList){
                Integer sort = WaitPurchaseProductEnum.getSortByWaitPurchaseProductSort(fieldAttrEntity.getAttr());
                fieldAttrEntity.setSort(sort);
            }
            headList.sort(Comparator.comparingInt(FieldAttrEntity::getSort));
        }
        // 智能补货列表页排序
        if ((Objects.isNull(fieldSort) || fieldSort.isEmpty())
                && Objects.equals(columnSetListDTO.getSubBusinessType(),XbbRefTypeEnum.SMART_REPLENISHMENT.getCode())){
            for (FieldAttrEntity fieldAttrEntity : headList){
                Integer sort = SmartReplenishmentEnum.getSortBySmartReplenishmentSort(fieldAttrEntity.getAttr());
                fieldAttrEntity.setSort(sort);
            }
            headList.sort(Comparator.comparingInt(FieldAttrEntity::getSort));
        }
        if (userConfigMap != null) {
            if (Objects.isNull(fieldSort) || fieldSort.isEmpty()) {
                return;
            }
            Map<String, Integer> attrAndSort = new HashMap<>(fieldSort.size());
            for (int i = 0; i < fieldSort.size(); i++) {
                JSONObject o = (JSONObject)fieldSort.get(i);
                attrAndSort.put(o.getString("attr"), o.getInteger("sort"));
            }
            headList.forEach(item-> {
                // 如果attrAndSort里没有，那么证明是新的字段，sort直接给它最大值
                item.setSort(attrAndSort.getOrDefault(item.getAttr(), headList.size()));
            });
            //dataList排序（列排序）
            headList.sort(Comparator.comparingInt(FieldAttrEntity::getSort));
        }
    }
}
